<template>
    <div class="home-container">
        <Header />
        <!-- 主要内容区域 -->
        <el-main class="main-content">
            <!-- 轮播图 -->
            <el-carousel height="320px" class="banner">
                <el-carousel-item v-for="item in bannerList" :key="item">
                    <el-image :src="item.cover" fit="cover" class="banner-item"></el-image>
                </el-carousel-item>
            </el-carousel>
            <div class="main-content_box">
                <div class="main-content_box_left">
                    <!-- 最新祭奠 -->
                    <div class="latest-memorials">
                        <Memorials :dataList="newGraveyardList" :familyList="familyList" />
                    </div>
                    <div class="articleModel">
                        <NewsPanel :cultureList="cultureList" :lifeList="lifeList" />
                    </div>
                </div>
                <div class="main-content_box_right">
                    <div class="main-content_box_right_login">
                        <LoginPanel />
                    </div>
                    <div class="main-content_box_right_heavenNews">
                        <HeavenNews :newList="newList" />
                    </div>

                </div>
            </div>
            <el-dialog v-model="isShowBingding" width="600">
                <el-form :model="registerForm" :rules="rules" ref="registerFormRef" label-width="120px"
				class="registration-form">
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model="registerForm.mobile" placeholder="请输入手机号" class="w-[280px]"></el-input>
                    </el-form-item>
                    <el-form-item label="登录密码" prop="password">
                        <el-input type="password" v-model="registerForm.password" placeholder="请输入登录密码" show-password class="w-[280px]"></el-input>
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname">
                        <el-input v-model="registerForm.nickname" placeholder="请输入昵称" class="w-[280px]"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <template #default>
                            <el-button type="primary" @click="binding">绑定</el-button>
                        </template>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </el-main>
        <el-dialog v-model="isQRcode" width="600">
            <div style="width: 100%;display: flex;justify-content: center;">
                <iframe
                    :src="qrcodeUrl"
                    frameborder="0"
                    scrolling="no"
                    width="300"
                    height="400"
                    sandbox="allow-scripts allow-top-navigation allow-same-origin allow-popups"
                ></iframe>
            </div>
        </el-dialog>
        <!-- 页脚 -->
        <Footer />
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import LoginPanel from '@/components/home/loginPanel.vue'
import NewsPanel from '@/components/home/NewsPanel.vue'
import HeavenNews from '@/components/home/heavenNews.vue'
import Header from '@/components/header/index.vue'
import Memorials from '@/components/home/memorials.vue'
import Footer from '@/components/footer/index.vue'
import useUserStore from '@/stores/modules/user';
import type { FormInstance, FormRules } from 'element-plus';
const userStore = useUserStore()
import { apiHomeData } from '@/api/home'
import feedback from '@/utils/feedback'
import { getToken } from '@/utils/auth'
const searchQuery = ref('')
const router = useRouter()
const route = useRoute()

const isQRcode = ref(false)
const qrcodeUrl = ref('') // 二维码地址
const isShowBingding = ref(false) // 是否显示绑定弹窗
// 表单数据模型
interface RegisterForm {
	nickname: string;
	mobile: string;
	password: string;
	channel: string;
    account?: string
}

const registerFormRef = ref<FormInstance>();

const registerForm = reactive<RegisterForm>({
	nickname: '',
	mobile: '',
	password: '',
	channel: '3'
});
const rules = reactive<FormRules<typeof registerForm>>({
	nickname: [
		{ required: true, message: '请输入用户名', trigger: 'blur' },
		{ min: 3, max: 15, message: '用户名长度在 3 到 15 个字符', trigger: 'blur' },
	],
	mobile: [
		{ required: true, message: '请输入手机号', trigger: 'blur' },
		{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
	],
	password: [
		{ required: true, message: '请输入登录密码', trigger: 'blur' },
		{ min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
	],
	
});

const binding = async () => {
    if (!registerFormRef.value) return;
    try {
		// 触发所有表单项的验证
		await registerFormRef.value.validate();

		// 如果验证通过，执行提交逻辑
		console.log('表单验证通过，准备提交:', registerForm);
        let obj = registerForm
        obj.account = registerForm.mobile
		// 在这里执行实际的注册 API 调用
		// const response = await api.register(registerForm);
		// ElMessage.success('注册成功！');
		// 重置表单
		// registerFormRef.value.resetFields();
		const userStore = useUserStore()
		await userStore.userUpData({...obj});
        isShowBingding.value = false
		router.push('/')
	} catch (error) {
		// 验证失败或提交失败
		console.error('表单验证失败或提交出错:', error);
		// ElMessage.error('注册失败，请检查填写的信息');
	}
}




// banner
const bannerList= ref([])
const newGraveyardList = ref([])
const familyList = ref([])
const cultureList = ref([])
const lifeList = ref([])
const newList = ref([])

const handleLogin = () => {
    // 处理登录逻辑
}

const handleRegister = () => {
    // 处理注册逻辑
}

const handleVisit = (id: string) => {
    // 处理访问纪念馆逻辑
    router.push(`/detail/${id}`)
}
const getHomeData = async () => {
    const data = await apiHomeData()
    console.log(data)
    bannerList.value = data.bannerList
    newGraveyardList.value = data.muList
    familyList.value = data.familyLIst
    cultureList.value = data.cultureList
    lifeList.value = data.lifeList
    newList.value = data.newList
}

onMounted( async () => {
    if(route.query.code){
        if(getToken()){
            userStore.bindCodeLogin(route.query.code as string).then((res: any)=>{
                console.log('res===========================',res)
                if(res.code != 1){
                    feedback.msgError(res.msg)
                }
                router.push('/')
            }).catch((err) => {
                // feedback.msgError(err.msg)
                router.push('/')
            })
        }else{
            console.log('code==============', route.query.code)
            userStore.handlerLogin(route.query.code as string, route.query.state as string).then((res: any) => {
                console.log('===================',res)
                if(res.mobile == ''){
                    console.log('弹起关联框')
                    isShowBingding.value = true
                }else{
                    router.push('/')
                }
            })
        }
        
        // isShowBingding.value = true
    }else{
        if(userStore.userInfo.has_auth === false){
            console.log('没有绑定微信')
            await feedback.confirm('您还没有绑定微信，绑定微信后可以微信登录，您要绑定吗？')
            isQRcode.value = true
            let url = 'https://cqjsyh.com/web/'
            let obj = await userStore.getLoginQrCode(url)
            console.log(obj)
            qrcodeUrl.value = obj?.url
        }
    }
    getHomeData()
    
})
</script>

<style scoped>
@import '@/styles/home.scss';

.main-content{
    width: 100%;
    min-width: 1200px;
    max-width: 1200px;
    margin: 0 auto;
    height: 100%;
    display: flex;
    flex-direction: column;
    margin-top: 20px;
}
.home-container {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}





.banner {
    margin-bottom: 40px;
    width: 100%;
    height: 100%;
}

.banner-item {
    width: 100%;
    max-width: 1200px;
    height: 100%;
    background-color: #d3dce6;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-size: 24px;
}



.latest-memorials {
    margin-bottom: 40px;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
}

.memorial-card {
    margin-bottom: 20px;
}

.memorial-card img {
    width: 100%;
    height: 200px;
    object-fit: cover;
}

.footer {
    background-color: #2c3e50;
    color: #fff;
    padding: 40px 0 20px;
}

.footer-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 40px;
}

.footer-section h3 {
    margin-bottom: 20px;
}

.social-links {
    display: flex;
    gap: 10px;
}

.copyright {
    text-align: center;
    margin-top: 40px;
    padding-top: 20px;
    border-top: 1px solid rgba(255, 255, 255, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {

    .top-content,
    .header-content {
        flex-direction: column;
        text-align: center;
        gap: 10px;
    }

    .search-box {
        flex-direction: column;
        width: 100%;
    }

    .search-input {
        width: 100%;
    }

    .main-menu {
        overflow-x: auto;
    }

    .footer-content {
        grid-template-columns: 1fr;
        gap: 20px;
    }
}
</style>